package com.sinogrand.elevator.repository

import android.content.Context
import android.util.Log
import com.sinogrand.elevator.data.models.ProjectListResponse
import com.google.gson.JsonObject
import com.sinogrand.elevator.network.NetworkClient
import com.sinogrand.elevator.utils.LogTags
import com.sinogrand.elevator.utils.PaginationUtils
import com.sinogrand.elevator.utils.Constants

/**
 * 项目仓库类
 */
class ProjectRepository(context: Context) {
    
    private val apiService = NetworkClient.getApiService(context)
    
    /**
     * 获取项目列表
     */
    suspend fun getProjectList(
        name: String? = null,
        type: Int? = null,
        page: Int = 1,
        size: Int = 20
    ): Result<ProjectListResponse> {
        return try {
            val request = JsonObject().apply {
                if (name != null) {
                    addProperty("name", name)
                }
                if (type != null) {
                    addProperty("type", type)
                }
                addProperty("page", page)
                addProperty("size", size)
            }
            val apiResponse = apiService.getProjectList(request)
            
            if (apiResponse.code == 0 && apiResponse.data != null) {
                val pageInfo = apiResponse.data.page_info
                
                Log.i(LogTags.API, "✅ 获取项目列表成功 - 总数: ${pageInfo.total}, 当前页: ${pageInfo.page}/${PaginationUtils.getTotalPages(pageInfo)}, 返回: ${apiResponse.data.list.size}条")
                Result.success(apiResponse.data)
            } else {
                Log.e(LogTags.API, "❌ 获取项目列表失败 - code: ${apiResponse.code}, msg: ${apiResponse.msg}")
                Result.failure(Exception(apiResponse.msg))
            }
        } catch (e: Exception) {
            Log.e(LogTags.API, "💥 获取项目列表异常 - ${e.javaClass.simpleName}: ${e.message}")
            Result.failure(e)
        }
    }
    
    /**
     * 获取安装项目列表
     */
    suspend fun getInstallProjectList(
        name: String? = null,
        page: Int = 1,
        size: Int = 20
    ): Result<ProjectListResponse> {
        return getProjectList(
            name = name,
            type = Constants.ProjectType.INSTALL,
            page = page,
            size = size
        )
    }
    
    /**
     * 获取维保项目列表
     */
    suspend fun getMaintenanceProjectList(
        name: String? = null,
        page: Int = 1,
        size: Int = 20
    ): Result<ProjectListResponse> {
        return getProjectList(
            name = name,
            type = Constants.ProjectType.MAINTENANCE,
            page = page,
            size = size
        )
    }
}
